﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace code
{
    public partial class Form1 : Form
    {
        DrawParameters drawParameters;//实例化DrawParameters，用来存储用户设置的绘画参数
        Color c;//用户在窗口中选择的颜色
        private Graphics graphics;
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (graphics == null)
            {
                setParameters();
                graphics = this.CreateGraphics();
                drawCayleyTree(drawParameters.Deepth,200,410, drawParameters.Lengh,-Math.PI/2);
            }
        }
        void setParameters()//从窗体应用中读取用户设置，传入DrawParameters
        {
            drawParameters.Deepth = int.Parse(textBox1.Text);
            drawParameters.Lengh = double.Parse(textBox2.Text);
            drawParameters.per1 = double.Parse(textBox7.Text);
            drawParameters.per2 = double.Parse(textBox6.Text);
            drawParameters.th1 = double.Parse(textBox5.Text) * Math.PI / 180;
            drawParameters.th2 = double.Parse(textBox4.Text)* Math.PI / 180;
            drawParameters.pen = new Pen(c);
        }
        void drawCayleyTree(int n,
                double x0, double y0, double leng, double th)
        {
            if (n == 0) return;

            double x1 = x0 + leng * Math.Cos(th);
            double y1 = y0 + leng * Math.Sin(th);

            drawLine(x0, y0, x1, y1);

            drawCayleyTree(n - 1, x1, y1, drawParameters.per1 * leng, th + drawParameters.th1);
            drawCayleyTree(n - 1, x1, y1, drawParameters.per1 * leng, th - drawParameters.th2);
        }
        void drawLine(double x0, double y0, double x1, double y1)
        {
            graphics.DrawLine(
                drawParameters.pen, (int)x0, (int)y0, (int)x1, (int)y1);
        }
        private void button2_Click(object sender, EventArgs e)
        {
            colorDialog1.ShowDialog();
            c = colorDialog1.Color;
            button2.Text = c.Name;
        }
    }
}